var ruleType;//团购2 闪购7,换购1
var timeSet;
var timeOut=0;
var OneMinBefore;//设定时间的前一分钟
//抢购属性
var mPayType = {};//统一的时间，但是每个窗口都有自己的支付方式
var mAddCart = {};//每个窗口自动加购物车的配置可以不同
//换购属性
var orderCode={};//换购订单号
var operateType={};
var today;
var activetabs;
var delay;

function run(i){
    var code='';
    var ctab = activetabs[i];
    var winId = ctab.windowId;
	if(operateType[winId]==1){//免单
		var productId = (mAddCart[winId]) ? mAddCart[winId] : null ;
	    code = "var ruleType="+ ruleType +";var timeOut=" + delay +";";
        code += "var payType=" + mPayType[winId] + ";var productId=" + productId + ";";
        chrome.tabs.executeScript(ctab.id,{code:code},function(){
            chrome.tabs.executeScript(ctab.id, {
                file:"freebuy.js"
            });
        });
	}else if(operateType[winId]==2){//换购
	    code += "var orderCodesForHuangou="+ orderCode[winId] +";var timeOut=" + delay +";";;
        chrome.tabs.executeScript(ctab.id,{code:code},function(){
            chrome.tabs.executeScript(ctab.id, {
                file:"huangou.js"
            });
        });
	}else if(operateType[winId]==3){//秒杀排队
        chrome.tabs.executeScript(ctab.id,{
            file:"seckill.js"
        });
	}else if(operateType[winId]==5){//一键购
        chrome.tabs.executeScript(ctab.id,{
            file:"yjg.js"
        });
	}
}
function notification(){
    var opt = {
        body:"小梨子出手啦！",
        icon:"timg.jpg"
    }
    var noti = new Notification("正在拼命抢...",opt);
    function closeNoti() {
        noti.close();
    }
    setTimeout(closeNoti,3000);
}

/**
 * 为每个window建立一个新窗口并试图去触发该窗口设置的对应免单类型
 */
function runEachWin(){
    console.log('run');
	timeSet = null;
    delay = (timeOut==0)?1:(timeOut*1000-1600);
	chrome.tabs.query({active:true},function(tabs){
	    console.log(tabs.length);
	    activetabs = tabs;
		for(var i = 0;i < tabs.length; i++){
			setTimeout('run('+ i +')',1);
		}
	});
}

/**
 * 跨域请求百度时间
 */
function checkTime() { 
    var xmlHttp = new XMLHttpRequest();
    var url = 'http://www.baidu.com/';
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4){
            if(xmlHttp.status==200){
                var head = xmlHttp.getResponseHeader('Date');
                console.log(head);
                var time = head.split(" ")[4].split(":");
			    var minute = parseInt(time[1]);
			    var second = time[2];
			    if(minute == timeSet){
			    	console.log("时间到触发!");
				   	runEachWin();
			    }else if(minute == OneMinBefore && second >= 59){//还有1秒以内
			    	setTimeout(runEachWin,950);
			    }else if(minute == OneMinBefore && second > 54){//还有5秒以内
			    	setTimeout(checkTime,1000);
			    }else if(minute > OneMinBefore+1){//清除计时
			    	timeSet = null;
			    }else{//5秒以上
			    	setTimeout(checkTime,5000);
			    }
            }
        }    
    }
    xmlHttp.open('get',url,true);
    xmlHttp.send(null);  
}

function setTimer(minute){//设置时间并启动计时器
	changeTimer(minute);
	console.log('now Time Set To Next:',minute);
	checkTime();
}

function changeTimer(minute){//改变计时器时间
	timeSet = minute;
	OneMinBefore = (minute-1)<0 ? 59 : (minute-1);
}

function initDate(){
	var date = new Date();
	var mon = date.getMonth() + 1;
	var day = date.getDate();
	today = date.getFullYear() + "-" + (mon<10?"0"+mon:mon) + "-" +(day<10?"0"+day:day);
	console.log('Today is',today);
}

function tryLoginCrm(No) {
    var loginUrl = 'http://crm.yihaodian.com/login/backendLogin.action';
    var data = "backOperatorDto.exactUserName=wangziqiao&backOperatorDto.originalPassword=Wzq12347&backOperatorDto.defaultAdminSiteId=1";
    $.ajax({
        type : 'POST',
        url:loginUrl,
        data:data,
        dataType:'text',
        success:function(data){
            if(data.indexOf("frameset")>-1){
                getSMSCode(No);
            }else{
                console.log('crm Login failed!');
            }
        }
    });
}
var maxCrmTry = 2;
function getSMSCode(No){
    if(!today){
        initDate();
    }
	var url = 'http://crm.yihaodian.com/edm/smsQueryByDto.action?smsQueryDto.startTime='+today+'&smsQueryDto.endTime='+today+'&smsQueryDto.source=&smsQueryDto.mobile='+No+'&smsQueryDto.channel=2&smsQueryDto.limit=20';
	var code = 'error';
	$.ajax({
		type : 'POST',
		url:url,
		dataType : 'html',
		async:false,
		success : function(data) {
			var pos = data.indexOf('验证码：');
			if(pos>=0){//请求到了验证码
				code = data.substring(pos+4,pos+10);
				console.log('本次验证码是：',code);
			}else{
			    maxCrmTry--;
			    //登录无效后重试一次
			    if(maxCrmTry>0){
			        tryLoginCrm(No);
			    }
				console.log('查不到验证码，是忘了登录Crm？');
			}
		}	
	});
	return code;
}
//获取验证码
chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
    if(request.greeting =="smsCode") {
    	var winId = sender.tab.windowId;
    	var smsCode = getSMSCode(request.No);
    	console.log('监听到了winId的请求：',winId);
    	sendResponse({smsCode:smsCode});
    }
});